package sharedServlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import controller.Controller;
import dataBase.Client;

@SuppressWarnings("serial")
public class CheckUserName extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		System.out.println("start");
		resp.setContentType("text/plain");
	    resp.setCharacterEncoding("UTF-8");
	    String userName = (String)req.getParameter("username");
	    String type = (String)req.getParameter("type");
	    PrintWriter  out = resp.getWriter();
	    System.out.println("username "+userName);
	    System.out.println("type "+type);
	    if(userName==null || userName.equals("") || type==null || type.equals("")){
	    	return;
	    }
	    boolean flag = checkUser(userName,type);		
	    
	    System.out.println("after check");
	    if(flag)
	    	if(type.equals("client"))
	    		out.print("<img src='images\\v-small.png'/> <font color='green'>This username is available</font>");
	    	else
	    		out.print("<img src='..\\images\\v-small.png'/> <font color='green'>This username is available</font>");
    	else
    		out.print("This username is taken");
	    resp.setStatus(200);
		out.flush();
		out.close();
	}
	
	
	private boolean checkUser(String userName, String type) {
	    Controller controller = Controller.getInstance();
	    if(type.equals("client")&&controller.getClient(userName)!=null)
	    	return false;
	    else if(type.equals("biz")&&controller.getBiz(userName)!=null)
	    	return false;
	    else if(type.equals("bizName")&&controller.bizNameToUserName(userName)!=null)
	    	return false;
	    return true;
	}


	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}
	
}

